/****************************************************************************
 * libwiigui Template
 * Tantric 2009
 *
 * demo.cpp
 * Basic template/demonstration of libwiigui capabilities. For a
 * full-featured app using many more extensions, check out Snes9x GX.
 ***************************************************************************/

#include <gccore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ogcsys.h>
#include <unistd.h>
#include <wiiuse/wpad.h>
#include <unistd.h>
#include <fat.h>
#include <sdcard/wiisd_io.h>


#include "FreeTypeGX.h"
#include "video.h"
#include "audio.h"
#include "menu.h"
#include "input.h"
#include "filelist.h"
#include "main.h"
#include "chan/cios.h"


FreeTypeGX *fontSystem;
int ExitRequested = 0;
const char* config = "SD:/guif/dash.conf";
struct SSettings Settings[10];
int dev=0;




void ExitApp()
{
	WriteConfig(config);
	ShutoffRumble();
	ShutdownAudio();
	StopGX();
	fatUnmount("SD");
	__io_wiisd.shutdown();
}


void
DefaultSettings()
{
	bool read = ReadConfig(config);
	if (read == false) {
	
		sprintf (Settings[0].ThemePath, "SD:/guif/theme/");
		sprintf (Settings[0].AppName,"USB Loader");
		sprintf (Settings[0].AppPath,"SD:/apps/usbloader/");
		sprintf (Settings[0].AppFile,"boot.dol");
		sprintf (Settings[1].AppName,"Wad Manager");
		sprintf (Settings[1].AppPath,"SD:/apps/wadmanager/");
		sprintf (Settings[1].AppFile,"boot.dol");
		sprintf (Settings[2].AppName,"mplayer_ce");
		sprintf (Settings[2].AppPath,"SD:/apps/mplayer_ce/");
		sprintf (Settings[2].AppFile,"boot.dol");
		sprintf (Settings[3].AppName,"Any Region");
		sprintf (Settings[3].AppPath,"SD:/apps/anyregion/");
		sprintf (Settings[3].AppFile,"boot.dol");
		sprintf (Settings[4].AppName,"Snes9X");
		sprintf (Settings[4].AppPath,"SD:/apps/snes9x/");
		sprintf (Settings[4].AppFile,"boot.dol");
		sprintf (Settings[5].AppName,"-1");
		WriteConfig(config);
	}	
}

int
main(int argc, char *argv[])
{
	
	PAD_Init();
	WPAD_Init();
	InitVideo(); // Initialise video
	InitAudio(); // Initialize audio

	// read wiimote accelerometer and IR data
	WPAD_SetDataFormat(WPAD_CHAN_ALL,WPAD_FMT_BTNS_ACC_IR);
	WPAD_SetVRes(WPAD_CHAN_ALL, screenwidth, screenheight);

	// Initialize font system
	fontSystem = new FreeTypeGX();
	fontSystem->loadFont(font_ttf, font_ttf_size, 0);
	fontSystem->setCompatibilityMode(FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_PASSCLR | FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_NONE);

	__io_wiisd.startup();
	fatMountSimple("SD", &__io_wiisd);
	InitGUIThreads();
	DefaultSettings();
	FirstMenu(MENU_MAIN);
}


// trim leading and trailing whitespace
// copy at max n or at max size-1
char* trim_n_copy(char *dest, char *src, int n, int size)
{
        int len;
        // trim leading white space
        while (isspace(*src)) { src++; n--; }
        len = strlen(src);
        if (len > n) len = n;
        // trim trailing white space
        while (len > 0 && isspace(src[len-1])) len--;
        if (len >= size) len = size-1;
        strncpy(dest, src, len);
        dest[len] = 0;
        //printf("trim_copy: '%s' %d\n", dest, len); //sleep(1);
        return dest;
}


char* trimcopy(char *dest, char *src, int size)
{
        int len;
        while (*src == ' ') src++;
        len = strlen(src);
        // trim trailing " \r\n"
        while (len > 0 && strchr(" \r\n", src[len-1])) len--;
        if (len >= size) len = size-1;
        strncpy(dest, src, len);
        dest[len] = 0;
        return dest;
}


// split line to part1 delimiter part2
bool trimsplit(char *line, char *part1, char *part2, char delim, int size)
{
        char *eq = strchr(line, delim);
        if (!eq) return false;
        trim_n_copy(part1, line, eq-line, size);
        trimcopy(part2, eq+1, size);
        return true;
}



bool WriteConfig(const char *fname)
{
		FILE *f;
        //printf("opening(%s)\n", fname);
        f = fopen(fname, "w");
        if (!f) {
                //printf("error opening(%s)\n", fname);
                return false;
        }
		
		fprintf(f, "# Replacement DashBoard By JQE\n");
        fprintf(f, "# Note: This file is automatically generated\n");
		fprintf(f, "Theme=%s\n", Settings[0].ThemePath);
		int i = 0;
		while (!strstr(Settings[i].AppName,"-1")) {
			fprintf(f, "App%iName=%s\n", i, Settings[i].AppName);
			fprintf(f, "App%iPath=%s\n", i, Settings[i].AppPath);
			fprintf(f, "App%iFile=%s\n", i, Settings[i].AppFile);
			i++;
		}

		fprintf(f, "App%iName=-1", i);
		fflush(f);
		fclose(f);
		return true;
}


bool ReadConfig(const char *fname)
{
		FILE *f;
        char line[200];
        //printf("opening(%s)\n", fname);
        f = fopen(fname, "r");
        if (!f) {
                //printf("error opening(%s)\n", fname);
                return false;
        }
		int k = 0;
        while (fgets(line, sizeof(line), f)) {

			bool comm;
			char opt_name[100], opt_val[100];
			comm = trimsplit(line, opt_name, opt_val, '=', sizeof(line));
			char * pch;
			pch = strstr (opt_val,"-1");
			if (pch) {
				sprintf(Settings[k].AppName, "-1");
				break;
			}
			pch = strstr(opt_name, "Theme");
			if (pch) {
				sprintf(Settings[0].ThemePath, "%s", opt_val);
				continue;
			}
			char *eq = strstr(opt_name, "Name");
			if (eq!=NULL) {
			sprintf(Settings[k].AppName, "%s", opt_val);
			}
			eq = strstr(opt_name, "Path");
			if(eq != NULL) {
			sprintf(Settings[k].AppPath, "%s", opt_val);
			}
			eq = strstr(opt_name, "File");
			if(eq != NULL) {
				sprintf(Settings[k].AppFile, "%s", opt_val);
			k++;
			}
		}
		
		fflush(f);
		fclose(f);
        return true;
}
